﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 修改人：郭文博
 * 时间：
 * 修改说明：
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.DbContest;

namespace seejee_Backendium.Data.Services
{
    public class UserAppService : IUserAPPsService
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<MenuService> _logger;
        public UserAppService(ApplicationDbContext context, ILogger<MenuService> logger)
        {
            _context = context;
            _logger = logger;
        }
        public async Task<IEnumerable<UserApp>> GetAllAsync()
        {
            return await _context.userApps
                   .AsNoTracking()
                   .ToListAsync();
        }

        public async Task<UserApp> GetByIdAsync(int id)
        {
            return await _context.userApps
                  .AsNoTracking()
                  .FirstOrDefaultAsync(ua => ua.id == id);
        }

        public async Task<IEnumerable<UserApp>> GetAllAsync(
        int page,
        int pageSize,
        string sortBy,
        string sortDirection)
        {
            var query = _context.userApps.AsNoTracking();

            // 动态排序 - 使用条件表达式
            query = sortBy.ToLower() switch
            {
                "id" => sortDirection.ToLower() == "desc"
                    ? query.OrderByDescending(ua => ua.id)
                    : query.OrderBy(ua => ua.id),
                "userName" => sortDirection.ToLower() == "desc"
                    ? query.OrderByDescending(ua => ua.userName)
                    : query.OrderBy(ua => ua.userName),
                "AppInformation" => sortDirection.ToLower() == "desc"
                    ? query.OrderByDescending(ua => ua.AppInformation)
                    : query.OrderBy(ua => ua.AppInformation),
                "appName" => sortDirection.ToLower() == "desc"
                   ? query.OrderByDescending(ua => ua.appName)
                   : query.OrderBy(ua => ua.appName),
                "updateTime" => sortDirection.ToLower() == "desc"
                   ? query.OrderByDescending(ua => ua.updateTime)
                   : query.OrderBy(ua => ua.updateTime),
                "appAddress" => sortDirection.ToLower() == "desc"
                   ? query.OrderByDescending(ua => ua.appAddress)
                   : query.OrderBy(ua => ua.appAddress),
                _ => query.OrderBy(ua => ua.userName) // 默认排序
            };
            // 分页
            return await query
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
        }
        public async Task<int> GetCountAsync()
        {
            return await _context.userApps.CountAsync();
        }
        //新增用户
        public async Task<UserApp> AddAsync(UserApp userApp)
        {
            // 检查是否已存在
            var existingUser = await _context.userApps
                .FirstOrDefaultAsync(ua => ua.userName == userApp.userName);
            //if (existingUser != null)
            //{
            //    throw new InvalidOperationException($"用户 {userApp.userName} 已存在");
            //}
            _context.userApps.Add(userApp);
            await _context.SaveChangesAsync();

            return userApp;
        }
        public async Task<int> DelectByNameAsync(int id)
        {
            var Users = await _context.userApps
                        .Where(ua => ua.id == id)
                        .ToListAsync();

            _context.userApps.RemoveRange(Users);
            return await _context.SaveChangesAsync();
        }
        public async Task<UserApp> UpdateAsync(UserApp userApp)
        {
            if (userApp.updateTime < new DateTime(1753, 1, 1) ||
                userApp.updateTime > new DateTime(9999, 12, 31))
            {
                userApp.updateTime = DateTime.Now; // 设为当前时间
            }
            // 获取现有实体（不跟踪）
            var existingEntity = await _context.userApps
                .AsNoTracking()
                .FirstOrDefaultAsync(u => u.userName == userApp.userName);

            if (existingEntity == null)
            {
                throw new InvalidOperationException($"用户 {userApp.userName} 不存在");
            }

            // 保留原始ID
            userApp.id = existingEntity.id;

            // 标记实体为已修改
            _context.Entry(userApp).State = EntityState.Modified;

            await _context.SaveChangesAsync();
            return userApp;
        }
        public async Task<IEnumerable<UserInfoDTO>> GetAllUserAsunc()
        {
            _logger.LogInformation("开始查询用户列表...");

            try
            {
                var sql = "SELECT * FROM CusUserList WHERE iCusPermissions = '1'";
                _logger.LogInformation($"执行SQL: {sql}");

                var users = await _context.UserInfoDTOs
                       .FromSqlRaw(sql)
                       .AsNoTracking()
                       .ToListAsync();

                _logger.LogInformation($"查询到 {users.Count} 条记录");
                return users;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询用户列表失败");
                throw;
            }
        }
        public async Task<(bool Success, IEnumerable<UserApp> Data, int Total, string Message)>SearchUsersAsync(string keyword, int page = 1, int pageSize = 10)
        {
            try
            {
                _logger.LogInformation("开始搜索用户，关键词: {Keyword}, 页码: {Page}, 页大小: {PageSize}",
                    keyword, page, pageSize);

                if (string.IsNullOrWhiteSpace(keyword))
                {
                    return (false, null, 0, "搜索关键词不能为空");
                }

                // 使用EF.Functions.Like实现模糊查询，性能更好
                var query = _context.userApps
                    .Where(u =>
                        EF.Functions.Like(u.userName, $"%{keyword}%") ||
                        EF.Functions.Like(u.AppInformation, $"%{keyword}%") ||
                        EF.Functions.Like(u.appName, $"%{keyword}%"))
                    .AsNoTracking();

                var total = await query.CountAsync();
                var users = await query
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                if (!users.Any())
                {
                    _logger.LogInformation("未找到匹配关键词 {Keyword} 的用户", keyword);
                    return (false, null, 0, $"未找到匹配关键词 '{keyword}' 的用户");
                }

                _logger.LogInformation("找到 {Count} 条匹配关键词 {Keyword} 的记录", users.Count, keyword);
                return (true, users, total, $"找到 {total} 条匹配记录");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索用户时发生错误");
                return (false, null, 0, $"搜索时发生错误: {ex.Message}");
            }
        }
    }
}
